﻿<link href="~/lib/layui/css/layui.css" rel="stylesheet" />
<script src="~/lib/layui/layui.js"></script>
<script src="~/lib/jquery/dist/jquery.js"></script>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>装配工单管理</title>
    <link href="//unpkg.com/layui@2.9.18/dist/css/layui.css" rel="stylesheet">
    <style>
        /* 自定义样式，使文本域宽度变宽 */
        .wide-textarea {
            width: 100%;
        }
    </style>
</head>
<body>
    <h3 style="text-align:center">装配工单添加页面</h3>

    <form class="layui-form" action="" style="margin:25px">
        <div>
            @* <input type="text" id="searchProcessNumber" placeholder="工序编号" class="layui-input" style="width: 300px; display: inline-block;">
            <input type="text" id="searchProcessName" placeholder="工序名称" class="layui-input" style="width: 300px; display: inline-block;"> *@
            <button type="button" class="layui-btn layui-bg-blue" onclick="search()">查询</button>
            <button type="button" class="layui-btn layui-bg-green" onclick="showAddForm()">新增</button>
            <button type="button" class="layui-btn layui-bg-green" onclick="showEditForm()">编辑</button>
            <button type="button" class="layui-btn layui-bg-green" onclick="customPrint()">自定义打印</button>
            @* <button type="button" class="layui-btn layui-bg-green" onclick="importData()">导入</button> *@
            <button type="button" class="layui-btn layui-bg-green" lay-event="import">导入</button>
            <button type="button" class="layui-btn layui-bg-green" onclick="exportData()">导出</button>
            <button type="button" class="layui-btn layui-bg-red" onclick="deleteData()">删除</button>
        </div>
    </form>

    <div style="margin:25px">
        <table id="processTable" class="layui-table">
            <thead>
                <tr>
                    <th><input type="checkbox" id="selectAll"></th>
                    <th>单据编号</th>
                    <th>工单数</th>
                    <th>已结束工单</th>
                    <th>单据进度</th>
                    <th>备注</th>
                    <th>创建时间</th>
                    <th>修改人</th>
                    <th>修改时间</th>
                </tr>
            </thead>
            <tbody>
                <!-- 添加了id属性 -->
                <!-- 装配工单列表数据将填充在这里 -->
            </tbody>
        </table>
    </div>

    <script src="//unpkg.com/layui@2.9.18/dist/layui.js"></script>
    <script src="//unpkg.com/jquery/dist/jquery.js"></script>
    <script>
        layui.use(['layer', 'form', 'element', 'table', 'upload', 'util'], function () {
            var layer = layui.layer;
            var form = layui.form;
            var element = layui.element;
            var table = layui.table;
            var util = layui.util;


            //导入execel
            util.on(
                'lay-event', {
               'import' : function () {
                    layer.open({
                        type: 2,
                        area: ['400px', '400px'],
                        shadeClose: true,
                        title: '导入装配工单',
                        content: '/Assembly/ImportAssmblyView'
                    })
                }
            }
            )

            // 全选和反选
            $('#selectAll').click(function () {
                $('.itemCheckbox').prop('checked', $(this).prop('checked'));
                form.render('checkbox');
            });

            // 单项选择时检查是否全选
            $('body').on('click', '.itemCheckbox', function () {
                if ($('.itemCheckbox:checked').length === $('.itemCheckbox').length) {
                    $('#selectAll').prop('checked', true);
                } else {
                    $('#selectAll').prop('checked', false);
                }
                form.render('checkbox');
            });

            // 显示新增工序的弹框
            window.showAddForm = function () {
                layer.open({
                    type: 1,
                    title: '新增装配工单',
                    area: ['900px', '600px'],
                    content: `
                                                                                        <form class="layui-form" id="addProcessForm">
                                                                                            <div class="layui-form-item">
                                                                                                <label class="layui-form-label">单据编号</label>
                                                                                                <div class="layui-input-inline">
                                                                                                    <input type="text" id="assemblyNumber" name="assemblyNumber" lay-verify="required" placeholder="请输入单据编号" class="layui-input">
                                                                                                </div>
                                                                                            </div>
                                                                                            <div class="layui-form-item">
                                                                                                <label class="layui-form-label">备注</label>
                                                                                                <div class="layui-input-inline wide-textarea">
                                                                                                    <textarea id="remark" name="remark" placeholder="请输入备注" class="layui-textarea"></textarea>
                                                                                                </div>
                                                                                            </div>
                                                                                            <div class="layui-form-item">
                                                                                                <button type="button" class="layui-btn" onclick="Add()">提交</button>
                                                                                            </div>
                                                                                                </form> <div style="left:500px"><h3>装配工单-产品明细</h3></div>
         <div class="layui-panel">
             <br />
             <!-- 按钮: 选择产品 -->
             <div>
                 <button class="layui-btn layui-btn-primary layui-border-blue" onclick="chans()" >+选择产品</button>
             </div>
             <!-- 表格 -->
             <div style="padding: 32px;">
                 <table class="layui-table">
                     <colgroup>
                         <col width="80">
                         <col width="150">
                         <col width="150">
                         <col width="150">
                         <col width="150">
                         <col width="150">
                         <col width="150">
                         <col width="150">
                         <col width="150">
                         <col width="150">
                         <col width="150">
                         <col width="150">
                         <col>
                     </colgroup>
                     <thead>
                         <tr >
                             <th style="text-align:center"><input type="checkbox" name="check" onclick="checkAll()" /></th>
                             <th style="text-align:center">层级编号</th>
                             <th style="text-align:center">产品编号</th>
                             <th style="text-align:center">产品名称</th>
                             <th style="text-align:center">产品规格</th>
                             <th style="text-align:center">工单编号</th>
                             <th style="text-align:center">数量</th>
                             <th style="text-align:center">完成数</th>
                             <th style="text-align:center">创建时间</th>
                             <th style="text-align:center">创建人</th>
                             <th style="text-align:center">修改人</th>
                             <th style="text-align:center">修改时间</th>
                         </tr>
                     </thead>
                     <tbody style="text-align:center">
                     </tbody>
                 </table>
                 <div id="demo-laypage-all"></div>
             </div>
         </div>
                                                                                    `
                });

                // 渲染表单元素
                form.render();
            };

            // 定义新增函数
            window.Add = function () {
                var assemblyNumber = document.getElementById('assemblyNumber').value;
                var remark = document.getElementById('remark').value;

                // 验证表单数据
                if (!assemblyNumber || !remark) {
                    layer.msg('请填写所有必填项');
                    return;
                }

                var requestData = {
                    assemblyNumber: assemblyNumber,
                    remark: remark,
                };

                // 发送 AJAX 请求
                fetch('@ViewBag.Durian' + '/api/Assembly/Handle', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(requestData)
                })
                    .then(response => response.json())
                    .then(data => {
                        layer.msg('新增成功');

                        layer.closeAll(); // 关闭弹框
                        search(); // 新增后加载工序列表
                    })
                    .catch(error => {
                        console.error('Error:', error);
                        layer.msg('新增失败');
                    });
            };

            $(function () {
                search();
            });

            // 加载工序列表
            function search() {
                $.post({
                    url: '@ViewBag.Durian' + '/api/Assembly/Handle1',
                    data: JSON.stringify({}), // 使用 JSON 格式
                    async: false,
                    dataType: "json",
                    contentType: "application/json",
                    success: res => {
                        console.log(res); // 修正控制台打印
                        var count = "";
                        $.each(res.data, function () {
                            count += `<tr>
                                                                                                      <td><input type="checkbox" class="itemCheckbox" value="${this.assemblyNumber}"></td>
                                                                                              <td>${this.assemblyNumber}</td>
                                                                                              <td>${this.assembliesNum}</td>
                                                                                              <td>0</td>
                                                                                              <td>
                                                                                                  <div class="layui-progress" lay-showpercent="true">
                                                                                                      <div class="layui-progress-bar" lay-percent="30%"></div>
                                                                                                  </div>
                                                                                              </td>
                                                                                              <td>${this.remark}</td>
                                                                                              <td>${this.createDate.replace("T", " ").substring(0, 19)}</td>
                                                                                              <td>${this.updateId}</td>
                                                                                              <td>${this.updateDate}</td>
                                                                                          </tr>`;
                        });
                        $("tbody").html(count);

                        // 渲染进度条
                        element.init();
                    }
                });
            };

            // 显示编辑工序的弹框
            window.showEditForm = function () {
                var selectedCheckboxes = $('.itemCheckbox:checked');
                if (selectedCheckboxes.length === 0) {
                    layer.msg('请选择一条记录进行编辑');
                    return;
                } else if (selectedCheckboxes.length > 1) {
                    layer.msg('只能选择一条记录进行编辑');
                    return;
                }

                var assemblyNumber = selectedCheckboxes.val();

                // 查找对应的行数据
                var rowData = null;
                $("#processTable tbody tr").each(function () {
                    if ($(this).find(".itemCheckbox").val() === assemblyNumber) {
                        rowData = {
                            assemblyNumber: $(this).find("td:eq(1)").text(),
                            assembliesNum: $(this).find("td:eq(2)").text(),
                            completedAssemblies: $(this).find("td:eq(3)").text(),
                            progress: $(this).find("td:eq(4) .layui-progress-bar").attr("lay-percent"),
                            remark: $(this).find("td:eq(5)").text(),
                            createDate: $(this).find("td:eq(6)").text(),
                            updateId: $(this).find("td:eq(7)").text(),
                            updateDate: $(this).find("td:eq(8)").text()
                        };
                        return false; // 停止循环
                    }
                });

                if (!rowData) {
                    layer.msg('未找到对应的数据');
                    return;
                }

                layer.open({
                    type: 1,
                    title: '编辑装配工单',
                    area: ['600px', 'auto'],
                    content: `
                                                                                        <form class="layui-form" id="editProcessForm">
                                                                                            <div class="layui-form-item">
                                                                                                <label class="layui-form-label">单据编号</label>
                                                                                                <div class="layui-input-inline">
                                                                                                    <input type="text" id="assemblyNumber" name="assemblyNumber" value="${rowData.assemblyNumber}" lay-verify="required" placeholder="请输入单据编号" class="layui-input" readonly>
                                                                                                </div>
                                                                                            </div>
                                                                                            <div class="layui-form-item">
                                                                                                <label class="layui-form-label">备注</label>
                                                                                                <div class="layui-input-inline wide-textarea">
                                                                                                    <textarea id="remark" name="remark" placeholder="请输入备注" class="layui-textarea">${rowData.remark}</textarea>
                                                                                                </div>
                                                                                            </div>
                                                                                            <div class="layui-form-item">
                                                                                                <button type="button" class="layui-btn" onclick="Edit()">提交</button>
                                                                                            </div>
                                                                                        </form>
                                                                                    `
                });

                // 渲染表单元素
                form.render();
            };

            // 定义编辑函数
            window.Edit = function () {
                var assemblyNumber = document.getElementById('assemblyNumber').value;
                var remark = document.getElementById('remark').value;

                // 验证表单数据
                if (!assemblyNumber || !remark) {
                    layer.msg('请填写所有必填项');
                    return;
                }

                var requestData = {
                    assemblyNumber: assemblyNumber,
                    remark: remark,
                };

                // 发送 AJAX 请求
                fetch('@ViewBag.Durian' + '/api/Assembly/Edit', {
                    method: 'PUT',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(requestData)
                })
                    .then(response => response.json())
                    .then(data => {
                        layer.msg('编辑成功');

                        layer.closeAll(); // 关闭弹框
                        search(); // 编辑后加载工序列表
                    })
                    .catch(error => {
                        console.error('Error:', error);
                        layer.msg('编辑失败');
                    });
            };

            // 批量删除功能
            window.deleteData = function () {
                var selectedCheckboxes = $(':checkbox:gt(0):checked');

                if (selectedCheckboxes.length === 0) {
                    layer.msg('请选择要删除的记录');
                    return;
                }
                //获取选中的ID
                var ids = "";
                selectedCheckboxes.each(function () {
                    ids += $(this).val() + ",";
                });
                ids = ids.substring(0, ids.length - 1); // 去掉最后一个逗号
                // alert(ids)

                // var assemblyNumbers = []; // 先定义空数组
                // selectedCheckboxes.each(function () {
                //     assemblyNumbers.push($(this).val()); // 填充选中的复选框值
                // });
                // var ids = $(":checkbox:gt(0):checked").map(function () {
                //     return $(this).val();
                //     }).get().join(","); // 获得选中的ID，并用逗号分隔
                //     alert(ids); // 输出选中的 ID，确保能够获得





                $.ajax({
                    url: '@ViewBag.Durian' + '/api/Assembly/Handle4',
                    type: 'DELETE',
                    data: JSON.stringify({ ids: ids }),
                    dataType: "json",
                    contentType: "application/json",
                    success: function (res) {
                        if (res.code == 1) {
                            layer.msg('删除成功');
                            search(); // 删除后加载工序列表
                        } else {
                            layer.msg('删除失败');
                        }
                    },
                    error: function (error) {
                        console.error('Error:', error);
                        layer.msg('删除失败');
                    }
                });
            };


        });

        function exportData() {
            location.href = '@ViewBag.Durian' + '/api/Assembly/ExportFarrowingsExcel';
        }


    </script>
</body>
</html>